package com.geekhale.validate.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
public class CustomControllerAdvice {
    @Autowired
    private BaseRequestValidator baseRequestValidator;

    public CustomControllerAdvice() {
    }

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        webDataBinder.addValidators(this.baseRequestValidator);
    }

    @ExceptionHandler
    @ResponseBody
    public String handleBindException(BindException exception){
        List<ObjectError> allErrors = exception.getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        for (ObjectError error : allErrors){
            String defaultMessage = error.getDefaultMessage();
            stringBuilder.append(defaultMessage)
                    .append("\n");
        }
        return stringBuilder.toString();
    }
}
